import random
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from os.path import join
from website.models import Queue, Song

class Command(BaseCommand):
    help = 'Grab a queued/random song from the database.  Used by liquidsoap.'

    def handle(self, *args, **options):
        try:
            filename = self.getQueuedSong()
            if filename == '':
                filename = self.getRandomSong()

            self.stdout.write(filename)
        except Exception:
            raise CommandError('Failed to select song.')


    def getQueuedSong(self):
        item = Queue.objects.first()
        if item is None:
            filename = ''
        else:
            song = item.song
            filename = join(settings.MEDIA_ROOT, song.file.name)
            item.delete()

        return filename


    def getRandomSong(self):
        try:
            songs = Song.objects.all()
            song = random.choice(songs)
            filename = join(settings.MEDIA_ROOT, song.file.name)
        except Exception:
            raise CommandError('Failed to select song.')
            filename = ''

        return filename
